import {
	toLogin,
	toGetInfo,
	toLogout
} from "@/api/login.js"
import {
	getToken,
	setToken,
	removeToken
} from '@/common/util/auth.js'

import {
	storage
} from "@/common/util/storage/index.js"

// const baseUrl = config.baseUrl
const user = {
	state: {
		token: getToken() || null,

		nick: storage.get('nick') || '',
		signature: storage.get('signature') || '',
		avatar: storage.get('avatar') || '',
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NICK: (state, nick) => {
			state.nick = nick
			storage.set('nick', nick)
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
			storage.set('avatar', avatar)
		},
		SET_SIGNATURE: (state, signature) => {
			state.signature = signature
			storage.set('signature', signature)
		}

	},

	actions: {
		// 登录
		Login({
			commit
		}, userInfo) {
			const username = userInfo.username.trim()
			const password = userInfo.password
			return new Promise((resolve, reject) => {
				toLogin({
					phoneNumber: username,
					password: password
				}).then(res => {
					setToken(res.data.token)
					commit('SET_TOKEN', res.data.token)
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetInfo({
			commit,
			state
		}, data) {
			return new Promise((resolve, reject) => {
				toGetInfo(data).then(res => {
					const {
						nick,
						avatar,
						signature
					} = res.data
					
						commit('SET_NICK', nick)
						commit('SET_AVATAR', avatar)
						commit('SET_SIGNATURE', signature)
						resolve(res)
				}).catch(error => {
					reject(123, error)
				})
			})
		},

		//   // 退出系统
		LogOut({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				toLogout().then(() => {
					commit('SET_TOKEN', '')
					removeToken()
					storage.clean()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}


export default user